package com.ljfiction.book.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.IsFirstPurseBean;
import com.ljfiction.book.Dialog.IsFirstPurseDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.PayPursDialog;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserBean;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.pay.PayResult;
import com.ljfiction.book.pay.WeiXin;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class PursActivity extends BaseActivity {

    @BindView(R.id.purse_over)
    TextView purseOver;
    @BindView(R.id.purse_recycle)
    RecyclerView purseRecycle;
    @BindView(R.id.purs_top)
    RelativeLayout pursTop;


    private List<String> lajibi = new ArrayList<>();
    private List<String> renminbi = new ArrayList<>();
    private List<String> zengsong = new ArrayList<>();
    private List<String> zengsongnum = new ArrayList<>();
    private PayPursDialog payPursDialog;
    private NoBackgLodDialog noBackgLodDialog;
private int mposition=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purs);
        ButterKnife.bind(this);
        if (UserManageBean.isLogin(this)) {
            purseOver.setText(String.valueOf(UserManageBean.userBean.getUserMoney()));
        }
        pursTop.getBackground().setAlpha(225);
        intview();
    }

    private void intview() {
        lajibi.add("600");
        lajibi.add("1200");
        renminbi.add("6");
        renminbi.add("12");
        zengsong.add("首充送600辣椒券+免费小说");
        zengsong.add("首充送1200辣椒券+免费小说");
        zengsongnum.add("");
        zengsongnum.add("");

        lajibi.add("3000");
        lajibi.add("5000");
        lajibi.add("9800");
        lajibi.add("19800");
        renminbi.add("30");
        renminbi.add("50");
        renminbi.add("98");
        renminbi.add("198");
        zengsong.add("首充送3000辣椒券+免费小说");
        zengsong.add("首充送5000辣椒券+免费小说");
        zengsong.add("首充送9800辣椒券+免费小说");
        zengsong.add("首充送19800辣椒券+免费小说");
        zengsongnum.add("150辣椒券");
        zengsongnum.add("300辣椒券");
        zengsongnum.add("800辣椒券");
        zengsongnum.add("1800辣椒券");
        purseRecycle.setLayoutManager(new GridLayoutManager(this, 2));
        BaseQuickAdapter<String, BaseViewHolder> adapter;
        purseRecycle.setAdapter(adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.purs_item, lajibi) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                if (helper.getLayoutPosition() > 1) {
                    helper.setText(R.id.purs_item_rmb, renminbi.get(helper.getLayoutPosition()))
                            .setText(R.id.purs_item_jia, "+")
                            .setText(R.id.purs_item_lj, item)
                            .setText(R.id.purs_item_zs, zengsongnum.get(helper.getLayoutPosition()))
                            .setText(R.id.purs_item_firstext, zengsong.get(helper.getLayoutPosition()));
                } else {
                    helper.setText(R.id.purs_item_rmb, renminbi.get(helper.getLayoutPosition()))
                            .setText(R.id.purs_item_jia, "")
                            .setText(R.id.purs_item_lj, "")
                            .setText(R.id.purs_item_zs, item)
                            .setText(R.id.purs_item_firstext, zengsong.get(helper.getLayoutPosition()));
                }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
              mposition =position;
                if (payPursDialog == null) {
                    payPursDialog = new PayPursDialog(PursActivity.this);
                    payPursDialog.setListener(new PayPursDialog.Listener() {
                        @Override
                        public void okClick(int isselect) {
                            if (!UserManageBean.isLogin(PursActivity.this)) {
                                showToast("你还没有登陆哦！先去登陆吧。");
                                return;
                            }
                            if (isselect == 1) {
                                //支付宝充值
                                OkHttpUtils.post(HttpManager.IP + "/api/muser/alipaySuccess.action")

                                        .params("userId", String.valueOf(UserManageBean.userBean.getUserId()))
                                        .params("userName", UserManageBean.userBean.getPseudonym())
                                        .params("total_fee", renminbi.get(mposition))
                                        .params("apymentType", "安卓")
                                        .params("channelId", UserManageBean.userBean.getUserCode())
                                        .params("rechargeChannelId", StringTool.getChannelName(PursActivity.this))
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onBefore(BaseRequest request) {
                                                super.onBefore(request);
                                                if (noBackgLodDialog == null) {
                                                    noBackgLodDialog = new NoBackgLodDialog(PursActivity.this, false);
                                                }
                                                noBackgLodDialog.show();
                                            }

                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                if (noBackgLodDialog != null && noBackgLodDialog.isShowing()) {
                                                    noBackgLodDialog.dismis();
                                                }
                                                try {
                                                    JSONObject jsonObject = new JSONObject(s);
                                                    if (jsonObject.getInt("returnCode") == 200) {
                                                        pay(jsonObject.getString("data"));

                                                    } else {
                                                        Toast.makeText(PursActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                            } else {


                                OkHttpUtils.post(HttpManager.IP + "/app/wxPayGetInfo")

                                        .params("nickName", UserManageBean.userBean.getPseudonym())
                                        .params("howmuch", renminbi.get(mposition))
                                        .params("channelId", UserManageBean.userBean.getUserCode())
                                        .params("rechargeChannelId", StringTool.getChannelName(PursActivity.this))
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onBefore(BaseRequest request) {
                                                super.onBefore(request);
                                                if (noBackgLodDialog == null) {
                                                    noBackgLodDialog = new NoBackgLodDialog(PursActivity.this, false);
                                                }
                                                noBackgLodDialog.show();
                                            }

                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                if (noBackgLodDialog != null && noBackgLodDialog.isShowing()) {
                                                    noBackgLodDialog.dismis();
                                                }
                                                JSONObject all;
                                                try {
                                                    all = new JSONObject(s);
                                                    if ("200".equals(StringTool.getStringByKeys(all, "-1", "returnCode"))) {
                                                        try {
                                                            JSONObject payInfo = all.getJSONObject("data");
                                                            WeiXin.Parame parame = new WeiXin.Parame();
                                                            parame.setAppId(StringTool.getStringByKeys(payInfo, "", "appid"));
                                                            parame.setTimeStamp(StringTool.getStringByKeys(payInfo, "", "timeStamp"));
                                                            parame.setSign(StringTool.getStringByKeys(payInfo, "", "sign"));
                                                            parame.setPartnerId(StringTool.getStringByKeys(payInfo, "", "partnerid"));
                                                            parame.setPrepayId(StringTool.getStringByKeys(payInfo, "", "prepayid"));
                                                            parame.setNonceStr(StringTool.getStringByKeys(payInfo, "", "nonceStr"));
                                                            new WeiXin().pay(PursActivity.this, parame);
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                            showToast("参数错误！");
                                                        }
                                                    } else {
                                                        if ("400".equals(StringTool.getStringByKeys(all, "-1", "returnCode"))) {
                                                            Intent intent = new Intent(PursActivity.this, LoginActivity.class);
                                                            startActivity(intent);
                                                        }
                                                        showToast(all.getString("msg"));
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }

                                            }
                                        });
                            }
                        }
                    });
                }
                payPursDialog.setPayNum(renminbi.get(mposition));
                payPursDialog.show();
            }
        });
    }

    @OnClick({R.id.purse_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.purse_back:
                goBack();
                break;
        }
    }


    private void pay(final String payInfo) {
        if (payInfo == null || payInfo.length() == 0) {
            Toast.makeText(PursActivity.this, "服务器获取支付信息异常", Toast.LENGTH_LONG).show();

        } else {

            Log.v("payInfo----?", payInfo + "");
            Runnable payRunnable = () -> {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PursActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(payInfo, true);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }


    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            if (msg.what == 1) {

                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                /*
                  同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                  detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                  docType=1) 建议商户依赖异步通知
                 */

                String resultStatus = payResult.getResultStatus();// 同步返回需要验证的信息
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if ((resultStatus.equals("9000"))) {
                    Toast.makeText(PursActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    changeRiches();
                    toisFirstpurs();
                } else {
                    // 判断resultStatus 为非"9000"则代表可能支付失败
                    // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (resultStatus.equals("8000")) {
                        Toast.makeText(PursActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        //mDialog.dismiss();
                    } else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        Toast.makeText(PursActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        //mDialog.dismiss();
                    }
                }

            }
        }
    };

    private void changeRiches() {
        OkHttpUtils.post(HttpManager.IP + "/person-info")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserManageBean.userBean = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                UserManageBean.setIsLogin(true);
                                purseOver.setText(String.valueOf(UserManageBean.userBean.getUserMoney()));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private IsFirstPurseDialog isFirstPurseDialog;

    private void toisFirstpurs() {
        OkHttpUtils.get(HttpManager.IP + "/getUserRechargerecordSum/" + renminbi.get(mposition) + "/" + UserManageBean.userBean.getPseudonym())

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        IsFirstPurseBean isFirstPurseBean = gson.fromJson(s, IsFirstPurseBean.class);
                        if (isFirstPurseBean.getReturnCode() == 200) {
                            if (isFirstPurseBean.getData().getOrderCount().equals("YES")) {
                                if (isFirstPurseDialog == null) {
                                    isFirstPurseDialog = new IsFirstPurseDialog(PursActivity.this, isFirstPurseBean.getData().getGiveBookInfo().getBookCover(), lajibi.get(mposition), isFirstPurseBean.getData().getGiveBookInfo().getBookName());
                                }
                                isFirstPurseDialog.show();
                            }
                        } else {
                            showToast(isFirstPurseBean.getMsg());
                        }
                    }
                });

    }



    @Override
    protected void onRestart() {
        super.onRestart();
        if (SettingManager.getInstance().getIsfirstPurse()==1){
            changeRiches();
            if (payPursDialog!=null){
                payPursDialog.thisdismiss();
            }
            toisFirstpurs();
            SettingManager.getInstance().saveIsfirstPurse(0);
        }
    }
}
